package com.example.javaproject.thread;

/**
 * Description:验证volatile
 * <pre>
 *     变量isRunning不加valatile时
 *     输出为
 *     -----
 *        进入run
 *        已赋值为false
 *     -----
 *
 *     添加后输出为
 *     --------
 *         进入run
 *         线程被停止了
 *         已赋值为false
 *     --------
 * <pre/>
 *
 *
 * <br>Author：tian
 * <br>Time: 2019/3/5 18:29
 */
public class ThreadDemo1 extends Thread {

    private volatile boolean isRunning = true;

    public boolean isRunning() {
        return isRunning;
    }

    public void setRunning(boolean running) {
        isRunning = running;
    }

    @Override
    public void run() {
        System.out.println("进入run");
        while (isRunning) {
        }
        System.out.println("线程被停止了");
    }

    public static void main(String[] args) {
        ThreadDemo1 threadOne = new ThreadDemo1();
        threadOne.start();

        new Thread(() ->
                threadOne.setRunning(false)
        ).start();

        try {
            threadOne.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("已赋值为false");
    }
}

